package service

import (
	"day12_12_homework/config"
	"day12_12_homework/internal/models/dao"
	"strconv"
	"time"
)

func FindFriend(myId int, friendId int) (string, string) {
	var user *dao.User
	err := config.DB.Model(&dao.User{}).Where("id=?", friendId).First(&user).Error
	if err != nil {
		return "", "用户不存在"
	}
	if user.ID == 0 {
		return "", "用户不存在"
	}
	var friends *dao.Friend
	err = config.DB.Debug().Model(&dao.Friend{}).Where("my_id=? && friend_id=?", myId, friendId).Limit(1).Find(&friends).Error
	if err != nil {
		return "", "已经添加过好友了"
	}
	if friends.ID != 0 {
		return "", "已经添加过好友了"
	}
	err = config.DB.Debug().Model(&dao.Friend{}).Where("my_id=? && friend_id=?", friendId, myId).Limit(1).Find(&friends).Error
	if err != nil {
		return "", "已经添加过好友了"
	}
	if friends.ID != 0 {
		return "", "已经添加过好友了"
	}
	return "", ""
}

func FriendCreate(userName string, id any) (string, string) {
	s := id.(string)
	myId, _ := strconv.Atoi(s)
	var user *dao.User
	err := config.DB.Model(&dao.User{}).Where("user_name=?", userName).First(&user).Error
	if err != nil {
		return "", "用户不存在"
	}
	if user.ID == 0 {
		return "", "用户不存在"
	}

	_, s2 := FindFriend(myId, int(user.ID))
	if s2 != "" {
		return "", s2
	}

	friendId := strconv.Itoa(int(user.ID))

	config.Rdb.Set(config.Ctx, "Create_friend_"+friendId, myId, time.Hour*24)

	return "已发送申请请耐心等待", ""
}

func Yes(myId int) (int, string) {
	get := config.Rdb.Get(config.Ctx, "Create_friend_"+strconv.Itoa(myId))
	friendId, _ := strconv.Atoi(get.Val())
	_, s2 := FindFriend(myId, friendId)
	if s2 != "" {
		return 0, s2
	}
	if get.Val() == "" {
		return 0, "好友添加失败"
	}

	friend := dao.Friend{
		MyId:     myId,
		FriendId: friendId,
	}
	friend1 := dao.Friend{
		MyId:     friendId,
		FriendId: myId,
	}

	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Error; err != nil {
		return 0, ""
	}

	err := tx.Model(&dao.Friend{}).Create(&friend).Error
	if err != nil {
		tx.Rollback()
		return 0, "好友添加失败"
	}
	err = tx.Model(&dao.Friend{}).Create(&friend1).Error
	if err != nil {
		tx.Rollback()
		return 0, "好友添加失败"
	}

	tx.Commit()

	config.Rdb.Del(config.Ctx, "Create_friend_"+strconv.Itoa(myId))

	return int(friend.ID), ""
}

func No(myId int) (string, string) {
	err := config.Rdb.Del(config.Ctx, "Create_friend_"+strconv.Itoa(myId)).Err()
	if err != nil {
		return "", "拒绝失败"
	}
	return "拒绝成功", ""
}

func Del(myId int, friendId int) string {
	err := config.DB.Model(&dao.Friend{}).Where("my_id=? && friend_id=?", myId, friendId).Error
	if err != nil {
		return "删除失败"
	}
	return ""
}
